<script setup>
  import { defineProps, onMounted, ref } from 'vue'
  import { http } from '@/utils/http.js'
  import { parseTime } from '@/utils/index.js'
  import { onLoad, onShow } from '@dcloudio/uni-app'

  // 我的发布列表
  const keywords = ref('')
  const isDown = ref(-1)
  const currentPage = ref(1)
  const dealList = ref([])
  async function getDealList() {
    const res = await http.request({
      url: '/api/bidding/myParticipate',
      method: 'POST',
      data: {
        page: currentPage.value,
        limit: 10,
        keywords: keywords.value,
        status: isDown.value,
      },
    })
    dealList.value = [...dealList.value, ...res.data]
    dealList.value.forEach((item) => {
      item.daysShort = item.order_pass_time - Math.floor(Date.now() / 1000)
      item.goods.forEach((goods) => {
        const currentTimestamp = Math.floor(Date.now() / 1000)
        let daysShort = goods.pass_time - currentTimestamp
        goods.passDay = Math.floor(daysShort / (24 * 60 * 60))
      })
    })
  }

  //搜索框
  function searchDeal() {
    currentPage.value = 1
    dealList.value = []
    getDealList()
  }

  //分类
  function chooseCategary(type) {
    if (isDown.value == type) {
      return
    }
    isDown.value = type
    dealList.value = []
    currentPage.value = 1
    getDealList()
  }

  //触底
  function dealListLower() {
    ++currentPage.value
    getDealList()
  }

  //查看出价
  function checkOffer(id) {
    uni.navigateTo({
      url: `/transactionPage/joinin/index?id=${id}`,
    })
  }

  function checkOfferDetail(id) {
    uni.navigateTo({
      url: `/transactionPage/offersuccess/index?id=${id}`,
    })
  }

  //去付款
  //删除地址
  const paypopup = ref()
  const payType = ref()
  const orderId = ref()
  const orderMoney = ref()
  const balance = ref()
  async function goPay(id, money) {
    await getUserInfo()
    orderId.value = id
    orderMoney.value = money
    paypopup.value.open('center')
  }

  // 选择付款方式
  const currentRadio = ref(1)
  function radioChange(e) {
    currentRadio.value = e.detail.value
  }

  function surePay() {
    if (currentRadio.value == 3) {
      xinshiPay()
    } else {
      wxPay()
    }
  }

  const emit = defineEmits(['doit'])
  async function xinshiPay() {
    const res = await http.request({
      url: '/api/bidding/balancePay',
      method: 'POST',
      data: {
        id: orderId.value,
        pay_type: currentRadio.value,
      },
    })
    if (res.st == 1) {
      uni.utils.toast('支付成功')
      emit('doit')
      dealList.value = []
      getDealList()
      paypopup.value.close()
    } else {
      uni.utils.toast(res.msg)
    }
  }

  const paying = ref(1)
  async function wxPay() {
    timeStatu.value = true
    const res = await http.request({
      url: '/api/adapay/adapay/adaPayOrder',
      method: 'POST',
      data: {
        id: orderId.value,
        type: 5,
        pay_type: currentRadio.value,
      },
    })

    if (res.st == 1) {
      uni.navigateToMiniProgram({
        appId: res.data.expend.wx_app_id,
        path: res.data.expend.path,
        extraData: {},
        success(res) {
          paying.value = 2
        },
      })
    } else {
      uni.utils.toast('拉起支付失败，请联系客服~')
    }
  }
  //微信官方支付
  // async function wxPay() {
  // 	const res = await http.request({
  // 		url: '/api/bidding/wechatPay',
  // 		method: 'POST',
  // 		data: {
  // 			id: orderId.value,
  // 			pay_type: currentRadio.value,
  // 		},
  // 	})
  // 	console.log(res)
  // 	if (res.st == 1) {
  // 		uni.requestPayment({
  // 			provider: 'wxpay',
  // 			timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
  // 			nonceStr: res.data.nonceStr, // 随机字符串
  // 			package: res.data.package, // 固定值
  // 			signType: res.data.signType,
  // 			paySign: res.data.paySign, // 签名，这里用的 MD5 签名
  // 			success: function (res) {
  // 				console.log('success:' + JSON.stringify(res))
  // 				if (res.errMsg == 'requestPayment:ok') {
  // 					setTimeout(() => {
  // 						timeStatu.value = false
  // 					}, 5000)
  // 					askOrder()
  // 				}
  // 			},
  // 			fail: function (err) {
  // 				uni.utils.toast('支付失败')
  // 				// console.log('fail:' + JSON.stringify(err))
  // 			},
  // 		})
  // 	} else {
  // 		uni.utils.toast(res.msg)
  // 	}
  // }

  // 微信支付
  //轮询微信支付订单状态
  const timeStatu = ref(true)
  async function askOrder() {
    setTimeout(() => {
      timeStatu.value = false
    }, 5000)
    const res = await http.request({
      url: '/api//bidding/getPayBagInfo',
      method: 'POST',
      data: {
        id: orderId.value,
      },
    })
    if (res.st == 1) {
      if (res.data.status == 2) {
        uni.utils.toast('支付成功')
        emit('doit')
        dealList.value = []
        getDealList()
        paypopup.value.close()
      } else {
        uni.utils.toast(res.data.pay_msg)
      }
    } else {
      if (timeStatu.value) {
        askOrder()
      } else {
        uni.utils.toast(res.msg)
      }
    }
    paying.value = 1
  }

  //商品详情弹出
  const goodspopup = ref()
  const goodsInfo = ref({
    goods_name: '',
    img: '',
  })
  function checkgoods(item) {
    console.log(item)
    goodsInfo.value = item
    goodspopup.value.open('bottom')
  }

  //获取星石

  async function getUserInfo() {
    const res = await http.request({
      url: '/api/user/userMsg',
      method: 'POST',
      data: {},
    })
    console.log('user')
    console.log(res.data)
    balance.value = res.data.data.balance
  }

  onMounted(() => {
    currentPage.value = 1
    isDown.value = -1
    dealList.value = []
    getDealList()
  })

  onShow(() => {
    if (paying.value == 2) {
      askOrder()
    }
  })
</script>

<template>
  <view>
    <view class="search">
      <uni-search-bar
        class="uni-mt-10"
        radius="100"
        placeholder="搜索..."
        clearButton="auto"
        cancelButton="none"
        @confirm="searchDeal"
        @clear="searchDeal"
        v-model="keywords"
        style="width: 100%"
      />

      <!-- <view class="avatar">
				<image
					style="width: 76rpx; height: 76rpx; border-radius: 50%"
					src="../../static/draw.png"
					mode=""
				></image>
				<view class="world-bar"> 发布 </view>
			</view> -->
    </view>
    <view class="screen">
      <view class="screen-left"> </view>
      <view class="screen-right">
        <view
          class="screen-right-item"
          @click="chooseCategary(-1)"
          :class="{ '.screen-right-item-active': isDown == -1 }"
        >
          待付款
        </view>
        <view
          class="screen-right-item"
          @click="chooseCategary(1)"
          :class="{ '.screen-right-item-active': isDown == 1 }"
        >
          竞拍中
        </view>
        <view
          class="screen-right-item"
          @click="chooseCategary(2)"
          :class="{ '.screen-right-item-active': isDown == 2 }"
        >
          已完成
        </view>
        <view
          class="screen-right-item"
          @click="chooseCategary(3)"
          :class="{ '.screen-right-item-active': isDown == 3 }"
        >
          已失效
        </view>
      </view>
    </view>
    <scroll-view
      scroll-y="true"
      class="scroll-Y"
      style="height: 80vh"
      @scrolltolower="dealListLower()"
    >
      <view class="deal-content">
        <view
          class="deal-content-item"
          v-for="item in dealList"
          :key="'deal' + item.id"
        >
          <view class="deal-content-item-top">
            <view class="deal-content-item-top-left">
              <view
                class=""
                style="
                  position: relative;
                  width: 88rpx;
                  height: 88rpx;
                  margin-right: 22rpx;
                "
              >
                <image
                  :src="item.himg"
                  style="width: 88rpx; height: 88rpx; border-radius: 50%"
                  mode=""
                ></image>
                <!-- <view
									class="back"
									style="
										position: absolute;
										bottom: 0;
										left: 50%;
										transform: translateX(-50%);
										width: 64rpx;
										height: 28rpx;
										border-radius: 14rpx;
										font-size: 16rpx;
										line-height: 28rpx;
										text-align: center;
									"
								>
									我的
								</view> -->
              </view>
              <view class="" style="font-size: 30rpx; font-weight: 700">
                {{ item.nickname }}
              </view>
            </view>
            <view
              class="top-time"
              style="font-size: 22rpx; color: #9b9b9d"
              v-if="item.status == 1 && item.order_id == 0"
            >
              {{ parseTime(item.add_time) }}
            </view>
            <view
              class="top-time"
              style="font-size: 28rpx; font-weight: 700"
              v-if="item.status == 1 && item.order_id > 0"
            >
              待付款：{{ item.order_money }}
            </view>
            <image
              v-else-if="item.status == 2"
              src="https://ojqn.wm2177.com/wechat_imgs/transition/deal-down.png"
              mode=""
              style="width: 100rpx; height: 100rpx; margin-right: 30rpx"
            ></image>
            <image
              v-else-if="item.status == 3"
              src="https://ojqn.wm2177.com/wechat_imgs/transition/deal-pass.png"
              mode=""
              style="width: 100rpx; height: 100rpx; margin-right: 30rpx"
            ></image>
          </view>
          <view class="deal-content-item-center">
            <scroll-view
              class="scroll-view_H"
              scroll-x="true"
              style="height: 150rpx; width: 100%"
            >
              <view class="scroll-view_H-list">
                <view
                  class="scroll-view_H-item"
                  style="position: relative"
                  v-for="goods in item.goods"
                  :key="'goods' + goods.id"
                  @click="checkgoods(goods)"
                >
                  <view v-if="goods.goods_num" class="goods_num" style="">
                    x{{ goods.goods_num }}
                  </view>
                  <image
                    :src="goods.img"
                    style="width: 130rpx; height: 130rpx; display: block"
                    mode=""
                  ></image>
                  <view class="presare" v-if="goods.type == 1"> 预售 </view>
                  <!-- 	<view v-else class="passTime">
										<image
											src="../../../static/pass.png"
											style="width: 16rpx; height: 16rpx"
											mode=""
										></image>
										<view
											class=""
											style="
												font-size: 12rpx;
												color: #fff;
											"
										>
											{{ goods.passDay }}天后自动发货
										</view>
									</view> -->
                </view>
              </view>
            </scroll-view>
            <view class="total-goods"> 共{{ item.num }}件 </view>
          </view>
          <view class="deal-content-item-bottom">
            <view class="deal-content-item-bottom-left">
              <view
                class=""
                v-if="!item.order_id"
                style="display: flex; align-items: center"
              >
                <!-- <view
									class="deal-content-item-bottom-left-item"
								>
									<image
										src="@/static/start-price.png"
										style="
											width: 42rpx;
											height: 42rpx;
											margin-right: 10rpx;
										"
										mode=""
									></image>
									<view
										class=""
										style="
											font-size: 20rpx;
											font-weight: 700;
										"
									>
										{{ item.min_price }}
									</view>
								</view> -->
                <view
                  class="deal-content-item-bottom-left-item"
                  v-if="item.is_buy == 1"
                >
                  <image
                    src="@/static/one-price.png"
                    style="width: 42rpx; height: 42rpx; margin-right: 10rpx"
                    mode=""
                  ></image>
                  <view class="" style="font-size: 20rpx; font-weight: 700">
                    {{ item.buy_price }}
                  </view>
                </view>
                <view class="deal-content-item-bottom-left-item">
                  <image
                    src="@/static/join-num.png"
                    style="width: 42rpx; height: 42rpx; margin-right: 10rpx"
                    mode=""
                  ></image>
                  <view class="" style="font-size: 20rpx; font-weight: 700">
                    {{ item.participate_num }}
                  </view>
                </view>
              </view>
              <view class="" style="display: flex; align-items: center" v-else>
                <image
                  src="@/static/hourglass.png"
                  mode=""
                  style="width: 60rpx; height: 60rpx; margin-right: 8rpx"
                ></image>
                <view class="" style="font-size: 26rpx">
                  <uni-countdown
                    :show-day="false"
                    :hour="
                      Math.floor((item.daysShort % (60 * 60 * 24)) / (60 * 60))
                    "
                    :minute="Math.floor((item.daysShort % (60 * 60)) / 60)"
                    :second="Math.floor(item.daysShort % 60)"
                  />
                </view>
                <image
                  src="https://ojqn.wm2177.com/wechat_imgs/transition/notice.gif"
                  style="width: 34rpx; height: 34rpx"
                  mode=""
                ></image>
              </view>
            </view>
            <view class="deal-content-item-bottom-right">
              <view
                class="price-button button"
                v-if="item.status == 1 && item.order_id == 0"
                @click="checkOffer(item.id)"
              >
                查看出价
              </view>
              <view
                class="price-button button"
                v-else-if="item.status == 1 && item.order_id > 0"
                @click="goPay(item.order_id, item.order_money)"
              >
                去付款
              </view>
              <view
                class="price-button button"
                v-else
                @click="checkOfferDetail(item.id)"
              >
                查看详情
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 付款弹出层 -->
    <uni-popup ref="paypopup" type="center">
      <view class="paypopup-content">
        <view class="paypopup-content-title"> 选择支付方式 </view>
        <view class="paypopup-content-money">
          <text style="font-size: 26rpx; color: #999999">需支付</text>
          <text style="font-size: 26rpx">￥</text>
          <text>{{ orderMoney }}</text>
        </view>
        <radio-group @change="radioChange">
          <view class="radio-item">
            <view class="radio-img">
              <image
                src="@/static/xinshi.png"
                style="
                  width: 52rpx;
                  height: 40rpx;
                  margin: 0 24rpx 0 40rpx;
                  border-radius: 50%;
                "
                mode=""
              ></image>
              <text style="font-size: 28rpx; line-height: 48rpx">星石支付</text>
              <text style="font-size: 22rpx; color: #9b9b9d"
                >（星石{{ balance }})</text
              >
            </view>
            <view style="margin-right: 40rpx">
              <radio
                color="#FFE60F"
                style="transform: scale(0.8)"
                value="3"
                :checked="currentRadio == 3"
              />
            </view>
          </view>
          <view class="radio-item">
            <view class="radio-img">
              <image
                src="../../../static/weixinpay2.png"
                style="
                  width: 48rpx;
                  height: 48rpx;
                  margin: 0 24rpx 0 40rpx;
                  border-radius: 50%;
                "
                mode=""
              ></image>
              <text style="font-size: 28rpx; line-height: 48rpx">微信</text>
            </view>
            <view style="margin-right: 40rpx">
              <radio
                color="#FFE60F"
                style="transform: scale(0.8)"
                value="1"
                :checked="currentRadio == 1"
              />
            </view>
          </view>
        </radio-group>
        <view class="bottom-button">
          <view
            class="button"
            style="margin-right: 48rpx; background-color: #eee"
            @click="paypopup.close()"
          >
            一会再说
          </view>
          <view class="button" @click="surePay"> 确认支付 </view>
        </view>
      </view>
    </uni-popup>

    <!-- 详情弹出层 -->
    <uni-popup ref="goodspopup" type="bottom">
      <view class="goodspopup-content">
        <view class="goods-title">{{ goodsInfo.goods_name }} </view>
        <image
          :src="goodsInfo.img"
          style="width: 660rpx; height: 660rpx"
          mode=""
        ></image>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  .goods_num {
    position: absolute;
    left: 50%;
    margin-left: -70rpx;
    width: 140rpx;
    z-index: 1;
    bottom: -30rpx;
    color: #333;
    height: 36rpx;
    text-align: center;
    line-height: 36rpx;
    border-radius: 100%;
    font-size: 22rpx;
  }
  .search {
    display: flex;
    align-items: center;
    background-color: #fff;
    .avatar {
      position: relative;
      width: 76rpx;
      height: 76rpx;
      border-radius: 50%;
      .world-bar {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 64rpx;
        height: 28rpx;
        border-radius: 14rpx;
        background-color: $transaction-color;
        text-align: center;
        line-height: 28rpx;
        font-size: 16rpx;
      }
    }
  }
  .screen {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    background-color: #fff;
    .screen-left {
      font-weight: 700;
      font-size: 28rpx;
    }
    .screen-right {
      display: flex;
      align-items: center;
      .screen-right-item {
        width: 130rpx;
        height: 58rpx;
        margin-right: 16rpx;
        box-sizing: border-box;
        background-color: #f7f7f7;
        border-radius: 29rpx;
        text-align: center;
        line-height: 58rpx;
        font-size: 24rpx;
        &:last-child {
          margin-right: 0;
        }
      }
      .screen-right-item-active {
        background-color: $transaction-color !important;
      }
    }
  }
  .deal-content {
    padding: 20rpx;
    .deal-content-item {
      height: 398rpx;
      margin-bottom: 20rpx;
      padding: 22rpx 18rpx 0 18rpx;
      box-sizing: border-box;
      border-radius: 12rpx;
      background-color: #fff;
      .deal-content-item-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .deal-content-item-top-left {
          display: flex;
          align-items: center;
        }
      }
      .deal-content-item-center {
        position: relative;
        height: 200rpx;
        padding: 32rpx 0;
        box-sizing: border-box;
        border-bottom: 6rpx solid #f5f5f5;
        .total-goods {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 92rpx;
          height: 46rpx;
          background-color: #eeeeee;
          font-size: 26rpx;
          line-height: 46rpx;
          text-align: center;
          color: #9b9b9d;
        }
        .scroll-view_H {
          .scroll-view_H-list {
            display: flex;
            flex-wrap: nowrap;
            .scroll-view_H-item {
              width: 130rpx;
              height: 130rpx;
              margin-right: 20rpx;
              box-sizing: border-box;
              &:last-child {
                margin-right: 0;
              }
              .presare {
                position: absolute;
                top: 0;
                right: 0;
                width: 54rpx;
                height: 28rpx;
                border-radius: 0 10rpx 0 0;
                background-color: rgba(0, 0, 0, 0.5);
                font-size: 20rpx;
                line-height: 28rpx;
                text-align: center;
                color: #fff;
              }
              .passTime {
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 100%;
                height: 28rpx;
                border-radius: 10rpx 10rpx 0 0;
                background-color: rgba(0, 0, 0, 0.5);
              }
            }
          }
        }
      }
      .deal-content-item-bottom {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 92rpx;
        .deal-content-item-bottom-left {
          display: flex;
          align-items: center;
          .deal-content-item-bottom-left-item {
            width: 134rpx;
            display: flex;
            align-items: center;
          }
        }
        .deal-content-item-bottom-right {
          .button {
            width: 158rpx;
            height: 58rpx;
            border-radius: 29rpx;
            background-color: $transaction-color;
            text-align: center;
            line-height: 58rpx;
            font-size: 24rpx;
            font-weight: 700;
          }
        }
      }
    }
  }
  ::v-deep .uni-searchbar {
    padding: 0;
    background-color: transparent;
  }
  ::v-deep .uni-searchbar__box {
    width: 100%;
    height: 72rpx !important;
    border: none !important;
    justify-content: start !important;
  }
  .back {
    background-color: $transaction-color;
  }

  .paypopup-content {
    width: 586rpx;
    height: 580rpx;
    box-sizing: border-box;
    border-radius: 44rpx;
    background-color: #fff;
    .paypopup-content-title {
      padding-top: 40rpx;
      margin-bottom: 30rpx;
      text-align: center;
      font-size: 30rpx;
    }
    .paypopup-content-money {
      height: 120rpx;
      line-height: 120rpx;
      background-color: #f5f5f5;
      font-size: 60rpx;
      text-align: center;
    }
    .radio-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 106rpx;
      .radio-img {
        display: flex;
        align-items: center;
      }
    }
    .bottom-button {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 10rpx;
      .button {
        width: 228rpx;
        height: 74rpx;
        border-radius: 37rpx;
        background-color: $transaction-color;
        font-size: 28rpx;
        text-align: center;
        line-height: 74rpx;
      }
    }
  }
  .goodspopup-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 886rpx;
    width: 710rpx;
    margin: 0 auto;
    padding-top: 36rpx;
    box-sizing: border-box;
    border-radius: 10rpx 10rpx 0 0;
    background-color: #fff;
    .goods-title {
      margin-bottom: 17rpx;
      font-size: 30rpx;
    }
  }
</style>
